package com.chatClient.ferradm.cs.newpaltz.edu;


import common.IMessageCollector;
import common.JoinRequest;
import common.NoConnection;
import common.TextMessage;

import dcf.BehaviorSchedule;
import dcf.BindNotificationMessage;
import dcf.Endpoint;
import dcf.IService;
import dcf.InitializationException;
import dcf.Message;
import dcf.UnboundNotificationMessage;




public class ChatClientBehavior extends BehaviorSchedule {
	
	boolean   isBound;
	IMessageCollector messageCollector;
	IService messageClientService;
	String userName;
	
	
	public ChatClientBehavior(Endpoint initLSEndpoint, Endpoint initLocalEndpoint) throws InitializationException {
		super(initLSEndpoint, initLocalEndpoint);
		isBound = false;
		
				messageClientService = createService("MsgClient", IService.ServiceType.SUBSCRIBER);
				
				
		
		
		
		//addService(messageClientService);
		

	}
		
	public void setMessageCollector(IMessageCollector newMessageCollector){
		messageCollector = newMessageCollector;
	}
	
	public void sendMessage(TextMessage message) throws NoConnection {
		
		if(isBound){
			System.out.println("CLIENT SEND MESSAGE :"+message.getMessageContent()+"  "+message.getSenderId()+"  "+message.getSenderEndpoint());
			messageClientService.send(message);		
		}
		else{
			System.out.println("No publisher was available to handle your request.");
			System.out.println("Please ensure a publisher is currently active and try again.");	
			throw new NoConnection();
		}

	}
	
	@Override
	public void interpretMessage(Message message) {
		
		if(message instanceof BindNotificationMessage){
			// TODO This should really only be set upon binding with the chat server.
			// It works so fix later.
			if (((BindNotificationMessage)message).getServiceName().equals(messageClientService.getServiceName())) {
				isBound = true;
				messageClientService.send(new JoinRequest(userName));
			}
			
		} else if (message instanceof UnboundNotificationMessage) {
			
			if(messageCollector != null){
			    messageCollector.addMessage(new TextMessage("System","** ChatServer is down. This is very bad. **"));
			}			
			
		} else if(message instanceof TextMessage){
			if(messageCollector != null){
			    messageCollector.addMessage((TextMessage)message);
			}
		}

	}

	
	public boolean isReady(){
		return isBound;
	}
	
	
	public void setUserName(String newUserName) {
		userName = newUserName;
	}
	
	
	// This operaion will shutdown the behavior. All services will be disconnected.
	// 
	// At this point in time, once shutdown, the behavior cannot be restarted.
	//
	public void shutDown() {
		messageClientService.send(new TextMessage(userName, " has left the chat."));
		deregisterService(messageClientService);
		messageCollector = null;

	}
	
	
}